"""
简化的WVP数据同步管理器
Simplified WVP Data Synchronization Manager

提供基本的WVP设备数据同步功能：
- 定时同步设备列表
- 简单的同步状态管理
- 基本的错误处理和重试
"""
import asyncio
import logging
from typing import Dict, List, Optional, Any
from datetime import datetime, timedelta
from dataclasses import dataclass
from enum import Enum

from .wvp_service import get_wvp_service, WVPDevice, WVPChannel

logger = logging.getLogger(__name__)


class SyncStatus(str, Enum):
    """同步状态枚举"""
    IDLE = "idle"
    RUNNING = "running"
    SUCCESS = "success"
    FAILED = "failed"


@dataclass
class SyncResult:
    """同步结果"""
    status: SyncStatus
    start_time: datetime
    end_time: Optional[datetime] = None
    total_devices: int = 0
    synced_devices: int = 0
    total_channels: int = 0
    synced_channels: int = 0
    error_message: Optional[str] = None
    
    @property
    def duration(self) -> Optional[float]:
        """同步持续时间（秒）"""
        if self.end_time and self.start_time:
            return (self.end_time - self.start_time).total_seconds()
        return None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "status": self.status.value,
            "start_time": self.start_time.isoformat(),
            "end_time": self.end_time.isoformat() if self.end_time else None,
            "duration": self.duration,
            "total_devices": self.total_devices,
            "synced_devices": self.synced_devices,
            "total_channels": self.total_channels,
            "synced_channels": self.synced_channels,
            "error_message": self.error_message
        }


class WVPSyncManager:
    """简化的WVP数据同步管理器"""
    
    def __init__(self, sync_interval: int = 300):  # 默认5分钟同步一次
        self.sync_interval = sync_interval
        self.wvp_service = get_wvp_service()
        
        # 同步状态
        self.current_status = SyncStatus.IDLE
        self.last_sync_result: Optional[SyncResult] = None
        self.sync_history: List[SyncResult] = []
        self.max_history = 10  # 保留最近10次同步记录
        
        # 同步任务
        self._sync_task: Optional[asyncio.Task] = None
        self._stop_event = asyncio.Event()
    
    async def start_sync_scheduler(self):
        """启动同步调度器"""
        if self._sync_task and not self._sync_task.done():
            logger.warning("同步调度器已在运行")
            return
        
        logger.info(f"启动WVP数据同步调度器，间隔: {self.sync_interval}秒")
        self._stop_event.clear()
        self._sync_task = asyncio.create_task(self._sync_loop())
    
    async def stop_sync_scheduler(self):
        """停止同步调度器"""
        logger.info("停止WVP数据同步调度器")
        self._stop_event.set()
        
        if self._sync_task:
            try:
                await asyncio.wait_for(self._sync_task, timeout=10.0)
            except asyncio.TimeoutError:
                logger.warning("同步任务停止超时，强制取消")
                self._sync_task.cancel()
    
    async def _sync_loop(self):
        """同步循环"""
        while not self._stop_event.is_set():
            try:
                # 执行完整同步（设备和通道）
                await self.sync_all()
                
                # 等待下次同步
                try:
                    await asyncio.wait_for(
                        self._stop_event.wait(), 
                        timeout=self.sync_interval
                    )
                    break  # 收到停止信号
                except asyncio.TimeoutError:
                    continue  # 超时，继续下次同步
                    
            except Exception as e:
                logger.error(f"同步循环异常: {e}")
                # 发生异常时等待一段时间再继续
                try:
                    await asyncio.wait_for(
                        self._stop_event.wait(), 
                        timeout=60  # 异常后等待1分钟
                    )
                    break
                except asyncio.TimeoutError:
                    continue
    
    async def sync_devices(self) -> SyncResult:
        """执行设备同步"""
        if self.current_status == SyncStatus.RUNNING:
            logger.warning("同步正在进行中，跳过本次同步")
            return self.last_sync_result
        
        logger.info("开始同步WVP设备数据")
        
        # 创建同步结果
        sync_result = SyncResult(
            status=SyncStatus.RUNNING,
            start_time=datetime.now()
        )
        
        self.current_status = SyncStatus.RUNNING
        
        try:
            # 获取设备列表
            devices = await self.wvp_service.get_devices(force_refresh=True)
            
            # 更新同步结果
            sync_result.total_devices = len(devices)
            sync_result.synced_devices = len(devices)
            sync_result.status = SyncStatus.SUCCESS
            sync_result.end_time = datetime.now()
            
            logger.info(f"设备同步成功，共同步 {len(devices)} 个设备")
            
        except Exception as e:
            error_msg = f"设备同步失败: {e}"
            logger.error(error_msg)
            
            sync_result.status = SyncStatus.FAILED
            sync_result.error_message = error_msg
            sync_result.end_time = datetime.now()
        
        # 更新状态和历史记录
        self.current_status = sync_result.status
        self.last_sync_result = sync_result
        self._add_to_history(sync_result)
        
        return sync_result
    
    def _add_to_history(self, sync_result: SyncResult):
        """添加到同步历史"""
        self.sync_history.append(sync_result)
        
        # 保持历史记录数量限制
        if len(self.sync_history) > self.max_history:
            self.sync_history = self.sync_history[-self.max_history:]
    
    def get_sync_status(self) -> Dict[str, Any]:
        """获取同步状态"""
        return {
            "current_status": self.current_status.value,
            "last_sync": self.last_sync_result.to_dict() if self.last_sync_result else None,
            "sync_interval": self.sync_interval,
            "is_scheduler_running": self._sync_task is not None and not self._sync_task.done()
        }
    
    def get_sync_history(self, limit: int = 10) -> List[Dict[str, Any]]:
        """获取同步历史"""
        history = self.sync_history[-limit:] if limit > 0 else self.sync_history
        return [result.to_dict() for result in history]
    
    async def manual_sync(self) -> SyncResult:
        """手动触发同步"""
        logger.info("手动触发WVP设备同步")
        return await self.sync_devices()


# 全局同步管理器实例
_sync_manager: Optional[WVPSyncManager] = None


def get_sync_manager() -> WVPSyncManager:
    """获取同步管理器实例"""
    global _sync_manager
    if _sync_manager is None:
        _sync_manager = WVPSyncManager()
    return _sync_manager


async def initialize_sync_manager():
    """初始化同步管理器"""
    sync_manager = get_sync_manager()
    await sync_manager.start_sync_scheduler()
    logger.info("WVP同步管理器初始化完成")


async def shutdown_sync_manager():
    """关闭同步管理器"""
    sync_manager = get_sync_manager()
    await sync_manager.stop_sync_scheduler()
    logger.info("WVP同步管理器已关闭")